# -*- encoding: utf-8 -*-

"""
------------------------------------------
@File       : kuaishou_test.py
@Author     : maixiaochai
@Email      : maixiaochai@outlook.com
@CreatedOn  : 2022/2/22 13:43
------------------------------------------
"""
import requests
import re


def AccessToRedirect(url, h):
    url = 'https://v.kuaishou.com/' + re.findall('https://v.kuaishou.com/([a-zA-Z0-9]+)', url)[0]

    r = requests.get(url, headers=h)
    location = r.url.split('?')[0].split('/')[-1]
    return location


def ForWithoutWatermark(location, h):
    url = 'https://video.kuaishou.com/graphql'

    data = {"operationName": "visionVideoDetail", "variables": {"photoId": location, "page": "detail"},
            "query": "query visionVideoDetail($photoId: String, $type: String, $page: String, $webPageArea: String) {\n  visionVideoDetail(photoId: $photoId, type: $type, page: $page, webPageArea: $webPageArea) {\n    status\n    type\n    author {\n      id\n      name\n      following\n      headerUrl\n      __typename\n    }\n    photo {\n      id\n      duration\n      caption\n      likeCount\n      realLikeCount\n      coverUrl\n      photoUrl\n      liked\n      timestamp\n      expTag\n      llsid\n      viewCount\n      videoRatio\n      stereoType\n      croppedPhotoUrl\n      manifest {\n        mediaType\n        businessType\n        version\n        adaptationSet {\n          id\n          duration\n          representation {\n            id\n            defaultSelect\n            backupUrl\n            codecs\n            url\n            height\n            width\n            avgBitrate\n            maxBitrate\n            m3u8Slice\n            qualityType\n            qualityLabel\n            frameRate\n            featureP2sp\n            hidden\n            disableAdaptive\n            __typename\n          }\n          __typename\n        }\n        __typename\n      }\n      __typename\n    }\n    tags {\n      type\n      name\n      __typename\n    }\n    commentLimit {\n      canAddComment\n      __typename\n    }\n    llsid\n    __typename\n  }\n}\n"}

    r = requests.post(url, json=data, headers=h).json()

    return r['data']['visionVideoDetail']['photo']['photoUrl'].split("&tt")[0]


if __name__ == '__main__':
    headers = {
        "Cookie": "填写你自己的cookie就可以了",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.81 Safari/537.36 SE 2.X MetaSr 1.0"
    }
    strcontent = input('请输入分享链接：')
    locat = AccessToRedirect(strcontent, headers)
    print("无水印视频链接：" + ForWithoutWatermark(locat, headers))
